package com.cloudkinto.service.order.impl;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.bo.order.OrderAmazonQueryBo;
import com.cloudkinto.common.constant.GlobalConstants;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.error.ErrorEnum;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.exception.BizExceptionI18;
import com.cloudkinto.common.exception.NotSufficientFundsException;
import com.cloudkinto.common.utils.AmazonUtil;
import com.cloudkinto.common.utils.ExcelUtils;
import com.cloudkinto.common.utils.StringsUtil;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.service.finance.CompanyAccountService;
import com.cloudkinto.service.operate.OperateRecordService;
import com.cloudkinto.service.operate.vo.OperateRes;
import com.cloudkinto.service.order.OrderAmazonService;
import com.cloudkinto.service.order.vo.amazon.*;
import com.cloudkinto.service.order.vo.amazon.amazonorder.ListOrdersResult;
import com.cloudkinto.service.order.vo.amazon.amazonorder.OrderItemsResponse;
import com.cloudkinto.service.orderoutput.OrderOutputService;
import com.cloudkinto.service.orderoutput.vo.OrderOutputAddReq;
import com.cloudkinto.service.orderoutput.vo.OrderOutputPackageAddReq;
import com.cloudkinto.service.orderoutput.vo.OrderOutputProductAddReq;
import com.cloudkinto.service.product.ProductInfoService;
import com.cloudkinto.service.region.JpRegionService;
import com.cloudkinto.service.shipprice.ShipPriceService;
import com.cloudkinto.service.shop.ShopService;
import com.cloudkinto.service.stock.StockRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author 张永远
 * @since 2020-06-02
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
@RequiredArgsConstructor
public class OrderAmazonServiceImpl extends ServiceImpl<OrderAmazonDao, OrderAmazonDo> implements OrderAmazonService {

    @Autowired
    private OrderAmazonDao dao;
    @Autowired
    private OrderAmazonItemsDao orderAmazonItemsDao;
    @Autowired
    private ShopDao shopDao;
//    @Autowired
    private OrderOutputDao orderOutputDao;
//    @Autowired
    private OrderOutputPackageDao orderOutputPackageDao;
    @Autowired
    private ProductSkuMapDao productSkuMapDao;
    @Autowired
    private ProductInfoDao productInfoDao;
//    @Autowired
    private ShopService shopService;
    @Autowired
    private OperateRecordService operateRecordDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CompanyAccountService companyAccountService;
    @Autowired
    private ShipPriceService shipPriceService;
    @Autowired
    private JpRegionService mRegionService;
    @Autowired
    private StockRecordDao stockDao;
    @Autowired
    private StorageDao storageDao;
    @Autowired
    private OrderOutputService outputService;
    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private StockRecordService stockRecordService;

    @Override
    public SingleResult addInit(Long userId, Long companyId) {
        List<Map> shopList = new ArrayList<>();
        UserDo userDo = userDao.selectById(userId);
        if (userDo == null) {
            throw new BizExceptionI18("no.user.info");
        }
        QueryWrapper shopWrapper = new QueryWrapper();
        if (userDo.getShopId() != null) {
            shopWrapper.eq("id", userDo.getShopId());
        }
        shopWrapper.eq("company_id", companyId);
        shopWrapper.eq("platform_id", 1);
        List<ShopDo> shopDoList = shopDao.selectList(shopWrapper);
        if (!CollectionUtils.isEmpty(shopDoList)) {
            for (ShopDo shopDo : shopDoList) {
                Map shopMap = new HashMap();
                shopMap.put("id", shopDo.getId());
                shopMap.put("value", shopDo.getShopName());
                shopList.add(shopMap);
            }
        }
        return SingleResult.success(shopList);
    }

    @Override
    public SingleResult downloadAmazonOrders(AmazonOrderDownReq req, Long userId, Long companyId) throws Exception {
        ShopDo shopDo = shopDao.selectById(req.getShopId());
        if (shopDo == null || StringUtils.isBlank(shopDo.getAmazonSellerId())) {
            throw new BizExceptionI18(SysConstant.SHOP_NO_TOKEN);
        }
        String now = new SimpleDateFormat(GlobalConstants.TIME_FORMAT_STR).format(new Date(System.currentTimeMillis() - 9 * 60 * 60 * 1000));
        String after = new SimpleDateFormat(GlobalConstants.TIME_FORMAT_STR).format(req.getBeforeDate().getTime() - 9 * 60 * 60 * 1000);
        String before = new SimpleDateFormat(GlobalConstants.TIME_FORMAT_STR).format(req.getAfterDate().getTime() + 15 * 60 * 60 * 1000);


        Map params = new HashMap();
        params.put("AWSAccessKeyId", GlobalConstants.amazonAccessKey);
        params.put("MWSAuthToken", shopDo.getAmazonToken());
        params.put("FulfillmentChannel", "MFN");
        params.put("SellerId", shopDo.getAmazonSellerId());
        params.put("MarketplaceId.Id.1", GlobalConstants.marketplaceId);

        Map itemMap = new HashMap(params);

        String result = AmazonUtil.doPostSubmitFeed(now, before, after, GlobalConstants.AmazonURL + "/Orders/2013-09-01", params, GlobalConstants.amazonSecret, "");

        try {
            JSONObject jsonResult = JSON.parseObject(result, JSONObject.class);
            //主表对象
            ListOrdersResult ordersResult = JSON.parseObject(jsonResult.getJSONObject("ListOrdersResponse").toJSONString(), ListOrdersResult.class);

            List<ListOrdersResult.ListOrdersResultEntity.OrdersEntity.OrderEntity> orderList = ordersResult.getListOrdersResult().get(0).getOrders().get(0).getOrder();

            if (!CollectionUtils.isEmpty(orderList)) {
                for (ListOrdersResult.ListOrdersResultEntity.OrdersEntity.OrderEntity orderEntity : orderList) {

                    itemMap.put("AmazonOrderId", orderEntity.getAmazonOrderId());
                    if (itemMap.containsKey("Signature")) {
                        itemMap.remove("Signature");
                    }
                    if (params.containsKey("LastUpdatedAfter")) {
                        params.remove("LastUpdatedAfter");
                    }
                    if (params.containsKey("LastUpdatedBefore")) {
                        params.remove("LastUpdatedBefore");
                    }
                    String resultItem = AmazonUtil.doPostSubmitFeedItem(now, GlobalConstants.AmazonURL + "/Orders/2013-09-01", itemMap, GlobalConstants.amazonSecret);
                    JSONObject itemJsonResult = JSON.parseObject(resultItem, JSONObject.class);

                    //附表对象
                    OrderItemsResponse itemsResponse = null;
                    try {
                        itemsResponse = JSON.parseObject(itemJsonResult.getJSONObject("ListOrderItemsResponse").toJSONString(), OrderItemsResponse.class);
                    } catch (Exception e) {
                    }

                    handlerOderInsert(req.getShopId(), companyId, orderEntity, itemsResponse);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return SingleResult.success();
    }

    @Override
    public void exportExcel(OrderAmazonQueryBo bo, HttpServletResponse response) throws IOException {
        List<OrderAmazonDo> orderAmazonDoList;

        if (CollectionUtils.isEmpty(bo.getIds())) {
            LambdaQueryWrapper<OrderAmazonDo> wrapper = queryBuild(bo);
            orderAmazonDoList = this.baseMapper.selectList(wrapper);
        } else {
            LambdaQueryWrapper<OrderAmazonDo> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(OrderAmazonDo::getId, bo.getIds())
                    .eq(Objects.nonNull(bo.getCompanyId()),OrderAmazonDo::getCompanyId, bo.getCompanyId())
                    .orderByDesc(OrderAmazonDo::getLastUpdateDate);
            orderAmazonDoList = this.baseMapper.selectList(wrapper);
        }
        if (orderAmazonDoList.size() > 5000) {
            throw new BizExceptionI18(SysConstant.Order_Count_Oversize_1000);
        }
        List<AmazonOrderExcelExportVo> excelExportVoList = new ArrayList<>();

        if (!CollectionUtils.isEmpty(orderAmazonDoList)) {
            LambdaQueryWrapper<OrderAmazonItemsDo> itemsWrapper;
            for (OrderAmazonDo orderAmazonDo : orderAmazonDoList) {
                AmazonOrderExcelExportVo excelExportVo = new AmazonOrderExcelExportVo();
                BeanUtils.copyProperties(orderAmazonDo, excelExportVo);

                itemsWrapper = new LambdaQueryWrapper<>();
                itemsWrapper.eq(OrderAmazonItemsDo::getOrderAmazonId, orderAmazonDo.getId());
                List<OrderAmazonItemsDo> itemsDoList = orderAmazonItemsDao.selectList(itemsWrapper);

                List<AmazonOrderItemExcelExportVo> itemExcelExportVoList = new ArrayList<>();
                if (!CollectionUtils.isEmpty(itemsDoList)) {
                    for (OrderAmazonItemsDo itemsDo : itemsDoList) {
                        AmazonOrderItemExcelExportVo itemExcelExportVo = new AmazonOrderItemExcelExportVo();
                        BeanUtils.copyProperties(itemsDo, itemExcelExportVo);
                        itemExcelExportVoList.add(itemExcelExportVo);
                    }
                }

                excelExportVo.setItemExcelExportVoList(itemExcelExportVoList);

                excelExportVoList.add(excelExportVo);
            }
        }
        ExcelUtils.exportExcel(excelExportVoList, AmazonOrderExcelExportVo.class, "亚马逊订单", new ExportParams(), response);
    }

    @Override
    public SingleResult markSendOut(List<Long> ids, Long userId) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new BizExceptionI18(SysConstant.PLS_CHOOSE_ORDER);
        }
        for (Long id : ids) {
            OrderAmazonDo orderAmazonDo = this.baseMapper.selectById(id);
            if (orderAmazonDo.getIsSendOut() == 0) {
                orderAmazonDo.setIsSendOut(1);
                this.baseMapper.updateById(orderAmazonDo);
                operateRecordDao.operateAddRecord(SysConstant.OPERATE_MARK_SEND, orderAmazonDo.getId(), userId, 4);
            }
        }
        return SingleResult.success();
    }

//    private void operateRecord(String str, OrderAmazonDo orderAmazonDo, Long userId) {
//        OperateRecordDo operateRecordDo = new OperateRecordDo();
//        operateRecordDo.setContent(str);
//        operateRecordDo.setOperateTime(new Date());
//        operateRecordDo.setOperateBy(userId);
//        operateRecordDo.setType(4);
//        operateRecordDo.setThirdId(orderAmazonDo.getId());
//        operateRecordDo.setDeleteFlag(0);
//        operateRecordDao.insert(operateRecordDo);
//    }

    @Override
    public SingleResult updateSysMemo(UpdateSysMemoReq req, Long userId, Long companyId) {
        OrderAmazonDo orderAmazonDo = this.baseMapper.selectById(req.getId());
        orderAmazonDo.setSystemMemo(req.getSystemMemo());
        this.baseMapper.updateById(orderAmazonDo);
        return SingleResult.success("编辑成功", null);
    }

    @Override
    public SingleResult systemMemoInit(Long id) {
        OrderAmazonDo orderAmazonDo = this.baseMapper.selectById(id);
        return SingleResult.success(orderAmazonDo.getSystemMemo());
    }

    @Override
    public SingleResult sendOut(String[] ids, Long userId, Long companyId, boolean isAuto) {
        sufficientFundsCheck(companyId);
        List<OrderOutputAddReq> orderOutputAddReqList = new ArrayList<>();
        List<String> failOrders = new ArrayList<>();
        ll:
        for (String id : ids) {
            OrderAmazonDo orderAmazonDo = this.baseMapper.selectById(id);
            if (orderAmazonDo == null) {
                failOrders.add(StringsUtil.createI18Message(SysConstant.NO_ORDER_INFO, orderAmazonDo.getAmazonOrderNumber()));
                continue;
            }
            if ("Canceled".equals(orderAmazonDo.getOrderStatus())) {
                failOrders.add(StringsUtil.createI18Message(SysConstant.ORDER_HAS_CANCEL_ID, orderAmazonDo.getAmazonOrderNumber()));
                continue;
            }
            LambdaQueryWrapper<OrderAmazonItemsDo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderAmazonItemsDo::getOrderAmazonId, id);
            List<OrderAmazonItemsDo> itemsDoList1 = orderAmazonItemsDao.selectList(wrapper);
            List<OrderOutputProductAddReq> itemsDoList = new ArrayList<>();
            for (OrderAmazonItemsDo productDo : itemsDoList1) {
                itemsDoList.addAll(productInfoService.getAddProductListByPlatformSku(orderAmazonDo.getCompanyId(),orderAmazonDo.getPurchaseDate(),
                        orderAmazonDo.getAmazonOrderNumber(),productDo.getSellerSku(),
                        productDo.getQuantityOrdered()-productDo.getQuantityShipped()>0? productDo.getQuantityOrdered()-productDo.getQuantityShipped(): productDo.getQuantityOrdered()));
            }
            //订单
            OrderOutputAddReq res = new OrderOutputAddReq();
            res.setOrderType(1);
            res.setPlatform("amazon");
            res.setPlatformNumber(orderAmazonDo.getId() + "");
            if (StringUtils.isNotBlank(orderAmazonDo.getPaymentCod())) {
                res.setCod((int) Double.parseDouble(orderAmazonDo.getPaymentCod()));
            }
            res.setSendDate(new Date());
            res.setShopId(orderAmazonDo.getShopId());
            res.setCompanyId(orderAmazonDo.getCompanyId());
            res.setOrderNo(orderAmazonDo.getAmazonOrderNumber());
            res.setReceiverName(orderAmazonDo.getShipName());
            res.setTelPhone(orderAmazonDo.getShipPhone());
            res.setPostCode(orderAmazonDo.getPostalCode());
            res.setArea(orderAmazonDo.getShipStateOrRegion());
            if (StringUtils.isNotBlank(orderAmazonDo.getShipCity())) {
                res.setAddress(orderAmazonDo.getShipCity() + orderAmazonDo.getShipAddress());
            } else {
                res.setAddress(orderAmazonDo.getShipAddress());
            }
            if (orderAmazonDo.getLastDeliveryDate() != null && orderAmazonDo.getEarliestDeliveryDate() != null &&
                    "Scheduled".equals(orderAmazonDo.getShipmentServiceLevelCategory())) {
                res.setDeliveryDate(TimeUtils.formatDate(orderAmazonDo.getLastDeliveryDate()));
                int time1 = Integer.parseInt(TimeUtils.formatDate(orderAmazonDo.getEarliestDeliveryDate(), "HH")) + 1;
                String startTime = time1 < 10 ? "0" + time1 : String.valueOf(time1);
                int time2 = Integer.parseInt(TimeUtils.formatDate(orderAmazonDo.getLastDeliveryDate(), "HH")) + 1;
                String endTime = time2 < 10 ? "0" + time2 : String.valueOf(time2);
                res.setDeliveryTime(startTime +
                        "-" + endTime);
            }
            long storageId = 0L;
            long stateId = 0;
            //item
            List<OrderOutputProductAddReq> orderOutputProductDetailList = new ArrayList<>();
            List<OrderOutputProductAddReq> failedItems = new ArrayList<>();
            if (!CollectionUtils.isEmpty(itemsDoList)) {
                double[] size = new double[4];
                double shipPirce = 99999D;
                //先看都有货的仓库
                LambdaQueryWrapper<StorageDo> lambdaQueryWrapper1 = new LambdaQueryWrapper();
                lambdaQueryWrapper1.eq(StorageDo::getSupportShip, 1);
                List<StorageDo> firstStorages = storageDao.selectList(lambdaQueryWrapper1);
                kk:
                for (StorageDo storageDo : firstStorages) {
                    for (OrderOutputProductAddReq itemsDo : itemsDoList) {

                        Long productId = getProductId(itemsDo.getCommoditySku(), orderAmazonDo.getCompanyId());
                        if (productId == null) {
                            failOrders.add(StringsUtil.createI18Message(SysConstant.ORDER_NO_SKU_INFO2_ID, orderAmazonDo.getAmazonOrderNumber(), itemsDo.getCommoditySku()));
                            continue ll;
                        }
                        // LambdaQueryWrapper<StockRecordDo> wrapper1 = new LambdaQueryWrapper();
                        // wrapper1.eq(StockRecordDo::getShopId, res.getShopId())
                        //         .eq(StockRecordDo::getProductInfoId, productId)
                        //         .eq(StockRecordDo::getStorageId, storageDo.getId());
                        // StockRecordDo stockRecordDo = stockDao.selectOne(wrapper1);
                        // if (stockRecordDo == null) {
                        //     continue kk;
                        // }
                        // int noDeliveredCount = stockDao.getOrderOutCount(productId, res.getShopId(), storageId)
                        //         + stockDao.getOrderOutTurn2FbaCount(productId, res.getShopId(), storageId);
                        int count = stockRecordService.getStockCount(orderAmazonDo.getCompanyId(), orderAmazonDo.getShopId(), storageDo.getId(), productId, itemsDo.getCount());
                        if (count < itemsDo.getCount()) {
                        // if (stockRecordDo.getCanSellCount() - noDeliveredCount < count) {//优先仓库有库存，优先仓库发货
                            continue kk;
                        }
                    }
                    //
                    storageId = storageDo.getId();
                }
                //默认仓库先捆包
                for (OrderOutputProductAddReq itemsDo : itemsDoList) {
                    Long productId = getProductId(itemsDo.getCommoditySku(), orderAmazonDo.getCompanyId());
                    if (productId == null) {
                        failOrders.add(StringsUtil.createI18Message(SysConstant.ORDER_NO_SKU_INFO2_ID, orderAmazonDo.getAmazonOrderNumber(), itemsDo.getCommoditySku()));
                        continue ll;
                    }
                    stateId = mRegionService.getStateIdByPostCode(orderAmazonDo.getPostalCode());
                    if (storageId != 0) {//大阪地区优先发货仓库
                    } else if (stateId <= 8) {//大阪地区优先发货仓库
                        storageId = 12L;
                        if ("NextDay".equals(orderAmazonDo.getOrderType())) {
                            storageId = 10L;
                        }
                    } else {//东京仓库优先发货仓库
                        storageId = 10L;
                    }
                    LambdaQueryWrapper<StockRecordDo> wrapper1 = new LambdaQueryWrapper();
                    wrapper1.eq(StockRecordDo::getShopId, res.getShopId())
                            .eq(StockRecordDo::getProductInfoId, productId)
                            .eq(StockRecordDo::getStorageId, storageId);
                    StockRecordDo stockRecordDo = stockDao.selectOne(wrapper1);
                    if (stockRecordDo == null) {
                        failedItems.add(itemsDo);
                        continue;
                    }
                    int count = stockRecordService.getStockCount(orderAmazonDo.getCompanyId(), orderAmazonDo.getShopId(), storageId, productId, itemsDo.getCount());
                    if (count <  itemsDo.getCount()) {//优先仓库有库存，优先仓库发货
                        failedItems.add(itemsDo);
                        continue;
                    }
                    OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
                    // productDetail.setOrderId(itemsDo.getOrderAmazonId());
                    productDetail.setProductId(productId);
                    productDetail.setCount(itemsDo.getCount());
                    orderOutputProductDetailList.add(productDetail);
                }
                OrderOutputPackageAddReq packageDetail = new OrderOutputPackageAddReq();
                List<OrderOutputPackageAddReq> packageAddReqList = new ArrayList<>();
                packageDetail.setProductList(orderOutputProductDetailList);
                OrderOutputAddReq addReq = new OrderOutputAddReq();
                BeanUtils.copyProperties(res, addReq);
                packageAddReqList.add(packageDetail);
                addReq.setStorageId(storageId);
                addReq.setPackageList(packageAddReqList);
                //默认仓库库存不足
                if (failedItems.size() != itemsDoList.size() && storageId != 0) {
//                if (failedItems.size() < 1 && storageId != 0) {
                    orderOutputAddReqList.add(addReq);
                } else {
                    failedItems = itemsDoList;
                } //一个仓库是否发完所有订单
                if (failedItems.size() > 0) {
                    List<OrderOutputProductAddReq> productAddList = new ArrayList<>();
                    //剩余一件商品无库存
                    if (failedItems.size() == 1 && failedItems.get(0).getCount() == 1) {
                        storageId = 0L;
                        Long productId = getProductId(failedItems.get(0).getCommoditySku(), res.getCompanyId());
                        List<StorageDo> storageDos = storageDao.selectList(null);
                        int count = failedItems.get(0).getCount();
                        if (count < 1) count = failedItems.get(0).getCount();
                        for (StorageDo storageDo : storageDos) {//遍历仓库是否都有库存
                            size = shipPriceService.countSameSkuSize(new double[4], productId, count);
                            int canUseCount = stockRecordService.getStockCount(orderAmazonDo.getCompanyId(), orderAmazonDo.getShopId(), storageDo.getId(), productId,count);
                            if (count <=  canUseCount)  {
                                List<ShipPriceDo> shipPriceDos = shipPriceService.queryByRegionAndSize(res.getPostCode(),
                                        size, res.getCod(), res.getShipmentType(), storageDo.getId(), 1, res.getCompanyId());
                                if (shipPriceDos.size() < 1 || shipPriceDos.get(0).getPrice() == 0) continue;
                                if (shipPirce > shipPriceDos.get(0).getPrice()) {//选择最便宜的价格
                                    shipPirce = shipPriceDos.get(0).getPrice();
                                    storageId = storageDo.getId();
                                }
                            }
                        }
                        OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
                        productDetail.setProductId(productId);
                        productDetail.setCount(count);
                        productAddList.add(productDetail);
                        OrderOutputPackageAddReq packageDetail1 = new OrderOutputPackageAddReq();
                        if (storageId != 0) {
                            List<OrderOutputPackageAddReq> packageAddReqList1 = new ArrayList<>();
                            packageDetail1.setProductList(productAddList);
                            OrderOutputAddReq addReq1 = new OrderOutputAddReq();
                            BeanUtils.copyProperties(res, addReq1);
                            packageAddReqList1.add(packageDetail1);
                            addReq1.setStorageId(storageId);
                            addReq1.setPackageList(packageAddReqList1);
//                            if (orderCount > 0) addReq.setOrderNo(addReq.getOrderNo() + "-" + orderCount);
//                            orderCount++;
                            orderOutputAddReqList.add(addReq1);
                        } else {
                            failOrders.add(StringsUtil.createI18Message(SysConstant.ORDER_NO_STOCK_ID, orderAmazonDo.getAmazonOrderNumber(), failedItems.get(0).getCommoditySku()));
                        }
                    } else {
                        List<OrderOutputProductAddReq> productAddList1 = new ArrayList<>();
                        //多件商品无库存，第二优先捆包
                        List<OrderOutputProductAddReq> productDoListFailed = new ArrayList<>();
                        List<OrderOutputProductAddReq> productDoListSuccess = new ArrayList<>();
                        LambdaQueryWrapper<StorageDo> lambdaQueryWrapper = new LambdaQueryWrapper();
                        lambdaQueryWrapper.eq(StorageDo::getSupportShip, 1)
                                .ne(StorageDo::getId, storageId);
                        if (stateId <= 8) {
                            lambdaQueryWrapper.orderByDesc(StorageDo::getStorageArea);
                        } else {
                            lambdaQueryWrapper.orderByAsc(StorageDo::getStorageArea);
                        }
                        List<StorageDo> storageDos = storageDao.selectList(lambdaQueryWrapper);
                        storageId = 0L;
                        if (storageDos != null) {
                            kk:
                            for (StorageDo storageDo : storageDos) {
                                ;//遍历支持捆包仓库是否都有库存
                                for (OrderOutputProductAddReq productDo :
                                        failedItems) {
                                    Long productId = getProductId(productDo.getCommoditySku(), res.getCompanyId());
                                    int count = productDo.getCount();
                                    // LambdaQueryWrapper<StockRecordDo> wrapper1 = new LambdaQueryWrapper();
                                    // wrapper1.eq(StockRecordDo::getShopId, res.getShopId())
                                    //         .eq(StockRecordDo::getProductInfoId, productId)
                                    //         .eq(StockRecordDo::getStorageId, storageDo.getId());
                                    // StockRecordDo stockRecordDo = stockDao.selectOne(wrapper1);
                                    // if (stockRecordDo == null) {
                                    //     productDoListSuccess.clear();
                                    //     productDoListFailed.clear();
                                    //     productAddList1.clear();
                                    //     productDoListFailed.addAll(failedItems);
                                    //     continue kk;
                                    // }
                                    // int noDeliveredCount = stockDao.getOrderOutCount(productId, res.getShopId(), storageDo.getId())
                                    //         + stockDao.getOrderOutTurn2FbaCount(productId, res.getShopId(), storageDo.getId());
                                    int canUseCount = stockRecordService.getStockCount(orderAmazonDo.getCompanyId(), orderAmazonDo.getShopId(), storageDo.getId(), productId,count);
                                    if (canUseCount < count) {
                                        productDoListSuccess.clear();
                                        productAddList1.clear();
                                        productDoListFailed.clear();
                                        productDoListFailed.addAll(failedItems);
                                        continue kk;
                                    } else {
                                        productDoListSuccess.add(productDo);
                                    }
                                    if (storageId != 0 && storageId != storageDo.getId()) {
                                        productAddList1.clear();
                                        productDoListSuccess.clear();
                                        productDoListFailed.clear();
                                    }
                                    storageId = storageDo.getId();
                                    OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
                                    productDetail.setProductId(productId);
                                    productDetail.setCount(count);
                                    productAddList1.add(productDetail);
                                }
                                if (productDoListSuccess.size() == failedItems.size()) {
                                    productDoListSuccess.clear();
                                    productDoListFailed.clear();
                                    packageDetail = new OrderOutputPackageAddReq();
                                    List<OrderOutputPackageAddReq> packageAddReqList1 = new ArrayList<>();
                                    packageDetail.setProductList(productAddList1);
                                    OrderOutputAddReq addReq1 = new OrderOutputAddReq();
                                    BeanUtils.copyProperties(res, addReq1);
                                    packageAddReqList1.add(packageDetail);
                                    if (storageId != 0) {
                                        addReq1.setStorageId(storageId);
                                        addReq1.setPackageList(packageAddReqList1);
                                        orderOutputAddReqList.add(addReq1);
                                        break kk;
                                    }
                                } else {
                                    productDoListSuccess.clear();
                                    productAddList1.clear();
                                    productDoListFailed.addAll(failedItems);
                                    continue kk;
                                }
                            }
                        } else {
                            productDoListFailed.addAll(failedItems);
                        }
                        List<OrderOutputProductAddReq> productAddList2 = new ArrayList<>();
                        //所有捆包仓库无库存的产品
                        if (productDoListFailed.size() > 0) {//捆包仓库无库存，分别发
                            LambdaQueryWrapper<StorageDo> queryWrapper = new LambdaQueryWrapper();
                            queryWrapper.eq(StorageDo::getCountryType, 1);
                            List<StorageDo> storageDoList = storageDao.selectList(queryWrapper);
                            for (OrderOutputProductAddReq productDo :
                                    productDoListFailed) {
                                storageId = 0L;
                                shipPirce = 99999D;
                                Long productId = getProductId(productDo.getCommoditySku(), res.getCompanyId());
                                int count = productDo.getCount();
                                for (StorageDo storageDo : storageDoList) {//遍历仓库是否都有库存
                                    LambdaQueryWrapper<StockRecordDo> wrapper2 = new LambdaQueryWrapper();
                                    size = shipPriceService.countSameSkuSize(new double[4], productId,
                                            1);
                                    // wrapper2.eq(StockRecordDo::getShopId, res.getShopId())
                                    //         .eq(StockRecordDo::getProductInfoId, productId)
                                    //         .eq(StockRecordDo::getStorageId, storageDo.getId());
                                    // StockRecordDo stockRecordDo1 = stockDao.selectOne(wrapper2);
                                    // int noDeliveredCount1 = stockDao.getOrderOutCount(productId, res.getShopId(), storageDo.getId())
                                    //         + stockDao.getOrderOutTurn2FbaCount(productId, res.getShopId(), storageDo.getId());
                                    int canUseCount = stockRecordService.getStockCount(orderAmazonDo.getCompanyId(), orderAmazonDo.getShopId(), storageDo.getId(), productId,count);
                                    if (canUseCount >= count) {
                                        List<ShipPriceDo> shipPriceDos = shipPriceService.queryByRegionAndSize(res.getPostCode(),
                                                size, res.getCod(), res.getShipmentType(), storageDo.getId(), 1, res.getCompanyId());
                                        if (shipPriceDos.size() < 1 || shipPriceDos.get(0).getPrice() == 0) continue;
                                        if (shipPirce > shipPriceDos.get(0).getPrice()) {//选择最便宜的价格
                                            shipPirce = shipPriceDos.get(0).getPrice();
                                            storageId = storageDo.getId();
                                        }
                                    }
                                }
                                if (storageId != 0) {
                                    OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
                                    productAddList2 = new ArrayList<>();
                                    productDetail.setProductId(productId);
                                    productDetail.setCount(count);
                                    productAddList2.add(productDetail);
                                    packageDetail = new OrderOutputPackageAddReq();
                                    packageAddReqList = new ArrayList<>();
                                    packageDetail.setProductList(productAddList2);
                                    addReq = new OrderOutputAddReq();
                                    BeanUtils.copyProperties(res, addReq);
                                    packageAddReqList.add(packageDetail);
                                    addReq.setStorageId(storageId);
                                    addReq.setPackageList(packageAddReqList);
//                                if (orderCount > 0) addReq.setOrderNo(addReq.getOrderNo() + "-" + orderCount);
//                                orderCount++;
                                    orderOutputAddReqList.add(addReq);
                                } else {
                                    //剩余SKU都没有库存
                                    failOrders.add(StringsUtil.createI18Message(SysConstant.ORDER_NO_STOCK_ID, orderAmazonDo.getAmazonOrderNumber(), failedItems.get(0).getCommoditySku()));
                                }
                            }
                        }
                    }
                }
            }
            if (orderOutputAddReqList.size() > 0) {
                // operateRecordDao.operateAddRecord(SysConstant.OPERATE_CLICK_SEND, orderAmazonDo.getId(), userId, 4);
            }
        }
        for (OrderOutputAddReq outputAddReq : orderOutputAddReqList) {
            StringBuilder sku = new StringBuilder();
            int cout = 0;
            for (OrderOutputProductAddReq orderOutputProductAddReq : outputAddReq.getPackageList().get(0).getProductList()) {
                cout = cout + orderOutputProductAddReq.getCount();
                if (StringUtils.isNotBlank(sku)) {
                    sku.append(",");
                }
                sku.append(productInfoDao.selectById(orderOutputProductAddReq.getProductId()).getCommoditySku());
            }
            outputAddReq.setSku(sku.toString());
            outputAddReq.setCount(cout);
        }
        if (isAuto) {
            sendOutMatch(orderOutputAddReqList, userId);
        }

        Map map = new HashMap();
        map.put("orderList", orderOutputAddReqList);
        map.put("failedList", failOrders);
        map.put("storageList", storageDao.selectList(null));
        return SingleResult.success(map);
    }

    @Override
    public SingleResult sendOutNopackage(String id, Long userId, Long companyId) {
        sufficientFundsCheck(companyId);
        List<OrderOutputAddReq> orderOutputAddReqList = new ArrayList<>();
        List<String> failOrders = new ArrayList<>();
        OrderAmazonDo orderAmazonDo = this.baseMapper.selectById(id);
        if (orderAmazonDo == null)
            throw new BizExceptionI18(SysConstant.NO_ORDER_INFO_ID, orderAmazonDo.getAmazonOrderNumber());
        if ("Canceled".equals(orderAmazonDo.getOrderStatus()))
            throw new BizExceptionI18(SysConstant.ORDER_HAS_CANCEL_ID, orderAmazonDo.getAmazonOrderNumber());
        LambdaQueryWrapper<OrderAmazonItemsDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderAmazonItemsDo::getOrderAmazonId, id);
        List<OrderAmazonItemsDo> itemsDoList1 = orderAmazonItemsDao.selectList(wrapper);
        List<OrderAmazonItemsDo> itemsDoList = new ArrayList<>();
        for (OrderAmazonItemsDo productDo : itemsDoList1) {
            if (productDo.getSellerSku().contains("+")) {
                for (String sku : productDo.getSellerSku().split("\\+")) {
                    OrderAmazonItemsDo productDo1 = new OrderAmazonItemsDo();
                    BeanUtils.copyProperties(productDo, productDo1);
                    productDo1.setSellerSku(sku);
                    itemsDoList.add(productDo1);
                }
            } else {
                itemsDoList.add(productDo);
            }
        }        //订单
        OrderOutputAddReq res = new OrderOutputAddReq();
        res.setOrderType(1);
        res.setPlatform("amazon");
        res.setPlatformNumber(orderAmazonDo.getId() + "");
        if (StringUtils.isNotBlank(orderAmazonDo.getPaymentCod()))
            res.setCod((int) Double.parseDouble(orderAmazonDo.getPaymentCod()));
        res.setSendDate(new Date());
        res.setShopId(orderAmazonDo.getShopId());
        res.setCompanyId(orderAmazonDo.getCompanyId());
        res.setOrderNo(orderAmazonDo.getAmazonOrderNumber());
        res.setReceiverName(orderAmazonDo.getShipName());
        res.setTelPhone(orderAmazonDo.getShipPhone());
        res.setPostCode(orderAmazonDo.getPostalCode());
        res.setArea(orderAmazonDo.getShipStateOrRegion());
        if (StringUtils.isNotBlank(orderAmazonDo.getShipCity())) {
            res.setAddress(orderAmazonDo.getShipCity() + orderAmazonDo.getShipAddress());
        } else {
            res.setAddress(orderAmazonDo.getShipAddress());
        }
        if (orderAmazonDo.getLastDeliveryDate() != null && orderAmazonDo.getEarliestDeliveryDate() != null &&
                "Scheduled".equals(orderAmazonDo.getShipmentServiceLevelCategory())) {
            try {
                res.setDeliveryDate(TimeUtils.formatDate(orderAmazonDo.getLastDeliveryDate()));
                int time1 = Integer.parseInt(TimeUtils.formatDate(orderAmazonDo.getEarliestDeliveryDate(), "HH")) + 1;
                String startTime = time1 < 10 ? "0" + time1 : String.valueOf(time1);
                int time2 = Integer.parseInt(TimeUtils.formatDate(orderAmazonDo.getLastDeliveryDate(), "HH")) + 1;
                String endTime = time2 < 10 ? "0" + time2 : String.valueOf(time2);
                res.setDeliveryTime(startTime +
                        "-" + endTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //item
        List<OrderOutputProductAddReq> orderOutputProductDetailList = new ArrayList<>();
        LambdaQueryWrapper<StorageDo> queryWrapper = new LambdaQueryWrapper();
        List<StorageDo> storageDoList = storageDao.selectList(queryWrapper);
        for (OrderAmazonItemsDo productDo :
                itemsDoList) {
            long storageId = 0L;
            double shipPirce = 99999D;
            int count = productDo.getQuantityOrdered() - productDo.getQuantityShipped();
            if (count < 1) count = productDo.getQuantityOrdered();
            Long productId = getProductId(productDo.getSellerSku(), res.getCompanyId());
            for (StorageDo storageDo : storageDoList) {//遍历仓库是否都有库存
                LambdaQueryWrapper<StockRecordDo> wrapper2 = new LambdaQueryWrapper();
                double[] size = shipPriceService.countSameSkuSize(new double[4], productId,
                        1);
                int canUseCount = stockRecordService.getStockCount(res.getCompanyId(), res.getShopId(), storageDo.getId(), productId,count);
                if (canUseCount >= count) {
                    List<ShipPriceDo> shipPriceDos = shipPriceService.queryByRegionAndSize(res.getPostCode(),
                            size, res.getCod(), res.getShipmentType(), storageDo.getId(), 1, res.getCompanyId());
                    if (shipPriceDos.size() < 1 || shipPriceDos.get(0).getPrice() == 0) continue;
                    if (shipPirce > shipPriceDos.get(0).getPrice()) {//选择最便宜的价格
                        shipPirce = shipPriceDos.get(0).getPrice();
                        storageId = storageDo.getId();
                    }
                }
            }
            if (storageId != 0) {
                OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
                productDetail.setProductId(productId);
                productDetail.setCount(count);
                List<OrderOutputProductAddReq> productAddList = new ArrayList<>();
                productAddList.add(productDetail);
                OrderOutputPackageAddReq packageDetail = new OrderOutputPackageAddReq();
                List<OrderOutputPackageAddReq> packageAddReqList = new ArrayList<>();
                packageDetail.setProductList(productAddList);
                OrderOutputAddReq addReq = new OrderOutputAddReq();
                BeanUtils.copyProperties(res, addReq);
                packageAddReqList.add(packageDetail);
                if (storageId != 0) {
                    addReq.setStorageId(storageId);
                    addReq.setPackageList(packageAddReqList);
                    orderOutputAddReqList.add(addReq);
                }
            } else {
                //剩余SKU都没有库存
                failOrders.add(StringsUtil.createI18Message(SysConstant.ORDER_NO_STOCK_ID, orderAmazonDo.getAmazonOrderNumber(), productDo.getSellerSku()));
            }

        }

        if (orderOutputAddReqList.size() > 0) {
            operateRecordDao.operateAddRecord(SysConstant.OPERATE_CLICK_SEND, orderAmazonDo.getId(), userId, 4);
        }
        for (OrderOutputAddReq outputAddReq : orderOutputAddReqList) {
            StringBuilder sku = new StringBuilder();
            int cout = 0;
            for (OrderOutputProductAddReq orderOutputProductAddReq : outputAddReq.getPackageList().get(0).getProductList()) {
                cout = cout + orderOutputProductAddReq.getCount();
                if (StringUtils.isNotBlank(sku)) {
                    sku.append(",");
                }
                sku.append(productInfoDao.selectById(orderOutputProductAddReq.getProductId()).getCommoditySku());
            }
            outputAddReq.setSku(sku.toString());
            outputAddReq.setCount(cout);
        }
        Map map = new HashMap();
        map.put("orderList", orderOutputAddReqList);
        map.put("failedList", failOrders);
        map.put("storageList", storageDao.selectList(null));
        return SingleResult.success(map);
    }

    @Override
    public SingleResult sendOutMatch(List<OrderOutputAddReq> orderOutputAddReqList, Long userId) {
        List<String> failOrders = new ArrayList<>();
        failOrders.addAll(outputService.addAmazonList(orderOutputAddReqList, userId));

//        return SingleResult.success(String.format("成功导出%d个发货单", orderOutputAddReqList.size() - failOrders.size()), failOrders);;
        if (failOrders.size() > 0) {
            return SingleResult.failure("300", SysConstant.EXPORT_OUT_ORDER_SUCCESS_ID, failOrders, orderOutputAddReqList.size() - failOrders.size());
        } else {
            return SingleResult.success(failOrders);
        }
    }

    private void sufficientFundsCheck(Long companyId) {
        if (!companyAccountService.getIsDue(companyId)) {
            throw new NotSufficientFundsException(ErrorEnum.NOT_SUFFICIENT_FUNDS);
        }
    }

    private Long getProductId(String sellerSku, Long companyId) {
        QueryWrapper productWrapper = new QueryWrapper();
        productWrapper.eq("commodity_sku", sellerSku);
        productWrapper.eq("company_id", companyId);
        productWrapper.last("limit 1");
        ProductInfoDo productInfoDo = productInfoDao.selectOne(productWrapper);
        if (productInfoDo == null) {
            QueryWrapper skuWrapper = new QueryWrapper();
            skuWrapper.eq("sub_sku", sellerSku);
            skuWrapper.eq("company_id", companyId);
            skuWrapper.last("limit 1");
            ProductSkuMapDo productSkuMapDo = productSkuMapDao.selectOne(skuWrapper);
            if (productSkuMapDo == null) return null;
            return productSkuMapDo.getProductInfoId();
        } else {
            return productInfoDo.getId();
        }
    }

    private Long getSubProductId(String sellerSku, Long companyId) {
        QueryWrapper skuWrapper = new QueryWrapper();
        skuWrapper.eq("sub_sku", sellerSku);
        skuWrapper.eq("company_id", companyId);
        ProductSkuMapDo productSkuMapDo = productSkuMapDao.selectOne(skuWrapper);
        if (productSkuMapDo == null) return null;
        return productSkuMapDo.getProductInfoId();
    }


    private OrderOutputPackageAddReq handlerPackage(List<OrderOutputProductAddReq> productInfoDoList) {
        OrderOutputPackageAddReq packageDetail = new OrderOutputPackageAddReq();
//        Float length = 0F;
//        Float width = 0F;
//        Float height = 0F;
//        Float weight = 0F;
//        if (!CollectionUtils.isEmpty(productInfoDoList)) {
//            for (ProductInfoDo productInfoDo : productInfoDoList) {
//                if (productInfoDo.getLength() > length) {
//                    length = productInfoDo.getLength();
//                }
//                if (productInfoDo.getWidth() > width) {
//                    width = productInfoDo.getWidth();
//                }
//                if (productInfoDo.getHeight() > height) {
//                    height = productInfoDo.getHeight();
//                }
//                weight += productInfoDo.getWeight();
//            }
//        }
//        Float volume = length * width * height;
//
//        packageDetail.setHeight(height.doubleValue());
//        packageDetail.setLength(length.doubleValue());
//        packageDetail.setWidth(width.doubleValue());
//        packageDetail.setWeight(weight.doubleValue());
//        packageDetail.setTrackId(null);
        //todo
        return packageDetail;
    }

    private void handlerOderInsert(Long shopId,
                                   Long companyId, ListOrdersResult.ListOrdersResultEntity.OrdersEntity.OrderEntity orderEntity, OrderItemsResponse
                                           itemsResponse) {
        QueryWrapper<OrderAmazonDo> wrapper = new QueryWrapper<>();
        wrapper.eq("amazon_order_number", orderEntity.getAmazonOrderId());
        OrderAmazonDo orderAmazonDo = dao.selectOne(wrapper);
        if (orderAmazonDo == null)
            orderAmazonDo = new OrderAmazonDo();
        orderAmazonDo.setAmazonOrderNumber(orderEntity.getAmazonOrderId());
        orderAmazonDo.setPurchaseDate(TimeUtils.getDateTime(orderEntity.getPurchaseDate()));  //2020-05-02T14:59:59Z
        orderAmazonDo.setLastUpdateDate(TimeUtils.getDateTime(orderEntity.getLastUpdateDate()));  //2020-05-02T14:59:59Z
        orderAmazonDo.setOrderStatus(orderEntity.getOrderStatus());
        orderAmazonDo.setFulfillmentChannel(orderEntity.getFulfillmentChannel());
        orderAmazonDo.setSalesChannel(orderEntity.getSalesChannel());
        orderAmazonDo.setShipServiceLevel(orderEntity.getShipServiceLevel());
        try {
            orderAmazonDo.setShipAddress(getStr(orderEntity.getShippingAddress().get(0).getAddressLine1()) + getStr(orderEntity.getShippingAddress().get(0).getAddressLine2()) + getStr(orderEntity.getShippingAddress().get(0).getAddressLine3()));
        } catch (Exception e) {
            log.error("Amazon地址转换错误" + e.getMessage());
        }
        orderAmazonDo.setSellerOrderNumber(orderEntity.getSellerOrderId());
        orderAmazonDo.setOrderChannel(orderEntity.getOrderChannel());
        if (!CollectionUtils.isEmpty(orderEntity.getShippingAddress())) {
            orderAmazonDo.setShipName(orderEntity.getShippingAddress().get(0).getName());
        }
        if (!CollectionUtils.isEmpty(orderEntity.getShippingAddress())) {
            orderAmazonDo.setShipCity(orderEntity.getShippingAddress().get(0).getCity());
        }
        if (!CollectionUtils.isEmpty(orderEntity.getShippingAddress())) {
            orderAmazonDo.setShipCounty(orderEntity.getShippingAddress().get(0).getCounty());
        }
        if (!CollectionUtils.isEmpty(orderEntity.getShippingAddress())) {
            orderAmazonDo.setShipDistrict(orderEntity.getShippingAddress().get(0).getDistrict());
        }
        if (!CollectionUtils.isEmpty(orderEntity.getShippingAddress())) {
            orderAmazonDo.setShipStateOrRegion(orderEntity.getShippingAddress().get(0).getStateOrRegion());
        }
        if (!CollectionUtils.isEmpty(orderEntity.getShippingAddress())) {
            orderAmazonDo.setPostalCode(orderEntity.getShippingAddress().get(0).getPostalCode()); //ship
        }
        if (!CollectionUtils.isEmpty(orderEntity.getShippingAddress())) {
            orderAmazonDo.setShipPhone(orderEntity.getShippingAddress().get(0).getPhone());
        }
        if (!CollectionUtils.isEmpty(orderEntity.getShippingAddress())) {
            orderAmazonDo.setShipAddressType(orderEntity.getShippingAddress().get(0).getAddressType());
        }
        if (!CollectionUtils.isEmpty(orderEntity.getOrderTotal())) {
            orderAmazonDo.setOrderTotal(orderEntity.getOrderTotal().get(0).getAmount()); //OrderTotalEntity
        }

        orderAmazonDo.setShipmentServiceLevelCategory(orderEntity.getShipmentServiceLevelCategory());
        orderAmazonDo.setPaymentMethod(orderEntity.getPaymentMethod());
        if ("COD".equals(orderEntity.getPaymentMethod())) {
            if (orderEntity.getPaymentExecutionDetail().size() > 0) {
                double sum = orderEntity.getPaymentExecutionDetail().stream().mapToDouble(paymentMethodDetailsEntity -> {
                    return Double.parseDouble(paymentMethodDetailsEntity.getPayment().getAmount());
                }).sum();
                orderAmazonDo.setPaymentCod(String.valueOf(sum));
            }
        }
        orderAmazonDo.setBuyerEmail(orderEntity.getBuyerEmail());
        orderAmazonDo.setBuyerName(orderEntity.getBuyerName());
        orderAmazonDo.setOrderType(orderEntity.getOrderType());
        orderAmazonDo.setEarliestShipDate(TimeUtils.getDateTime2(orderEntity.getEarliestShipDate()));
        orderAmazonDo.setLastShipDate(TimeUtils.getDateTime2(orderEntity.getLatestShipDate()));
        orderAmazonDo.setEarliestDeliveryDate(TimeUtils.getDateTime2(orderEntity.getEarliestDeliveryDate()));
        orderAmazonDo.setLastDeliveryDate(TimeUtils.getDateTime2(orderEntity.getLatestDeliveryDate()));
        orderAmazonDo.setPurchaseOrderNumber(orderEntity.getPurchaseOrderNumber());
        orderAmazonDo.setIsSendOut(0);
        orderAmazonDo.setIsUploadTrackNo(0);
        orderAmazonDo.setShopId(shopId);
        orderAmazonDo.setCompanyId(companyId);

        StringBuilder sb = new StringBuilder();
        if (itemsResponse != null) {
            for (OrderItemsResponse.ListOrderItemsResultEntity.OrderItemsEntity.OrderItemEntity itemEntity : itemsResponse.getListOrderItemsResult().get(0).getOrderItems().get(0).getOrderItem()) {
                if (sb.length() > 1) {
                    sb.append(",");
                }
                if (shopId == 1) {
                    sb.append(itemEntity.getSellerSKU().replaceAll("BFBA-", "").replaceAll("FBA-", ""));
                } else {
                    sb.append(itemEntity.getSellerSKU());
                }
            }
            orderAmazonDo.setCommoditySku(sb.toString());
        }

        if (orderAmazonDo.getId() == null || orderAmazonDo.getId() == 0) {
            dao.insert(orderAmazonDo);
        } else {
            dao.updateById(orderAmazonDo);
        }
        if (itemsResponse == null) {
            return;
        }
        for (OrderItemsResponse.ListOrderItemsResultEntity.OrderItemsEntity.OrderItemEntity itemEntity : itemsResponse.getListOrderItemsResult().get(0).getOrderItems().get(0).getOrderItem()) {
            OrderAmazonItemsDo itemsDo = new OrderAmazonItemsDo();
            itemsDo.setOrderAmazonId(orderAmazonDo.getId());
            itemsDo.setAsin(itemEntity.getASIN());
            itemsDo.setTitle(itemEntity.getTitle());
            if (shopId == 1) {
                itemsDo.setSellerSku(itemEntity.getSellerSKU().replaceAll("BFBA-", "").replaceAll("FBA-", ""));
            } else {
                itemsDo.setSellerSku(itemEntity.getSellerSKU());
            }
            Long productId = getProductId(itemsDo.getSellerSku(), companyId);
            itemsDo.setSystemSku(productId);
            itemsDo.setTitle(itemEntity.getTitle());
            try {
                itemsDo.setQuantityOrdered(Integer.parseInt(itemEntity.getQuantityOrdered()));
                itemsDo.setQuantityShipped(Integer.parseInt(itemEntity.getQuantityShipped()));
            } catch (Exception e) {

            }

            if (!CollectionUtils.isEmpty(itemEntity.getItemPrice())) {
                itemsDo.setItemPrice(itemEntity.getItemPrice().get(0).getAmount());
            }
            if (!CollectionUtils.isEmpty(itemEntity.getCODFee())) {
                itemsDo.setCodFee(itemEntity.getCODFee().get(0).getAmount());
            }
            itemsDo.setItemId(itemEntity.getOrderItemId());
            itemsDo.setIsGift(StringUtils.isNotBlank(itemEntity.getIsGift()) && "true".equals(itemEntity.getIsGift()) ? 1 : 0);
            QueryWrapper wrapper1 = new QueryWrapper();
            wrapper1.eq("item_id", itemsDo.getItemId());
            OrderAmazonItemsDo amazonItemsDo = orderAmazonItemsDao.selectOne(wrapper1);
            if (amazonItemsDo == null) {
                orderAmazonItemsDao.insert(itemsDo);
            } else {
                itemsDo.setId(amazonItemsDo.getId());
                orderAmazonItemsDao.updateById(itemsDo);
            }
        }

//todo 自动到出
//        sendOut()
    }

    @Override
    public Object add(Object req, Long userId) {
        OrderAmazonDo entityDo = new OrderAmazonDo();
        BeanUtils.copyProperties(req, entityDo);
        handlerAddBefore(entityDo, userId);
        dao.insert(entityDo);
        return handlerAddAfter(entityDo);
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(OrderAmazonDo entityDo, Long userId) {
//        entityDo.setCreateBy(userId);
//        entityDo.setCreateTime(new Date());
//        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(OrderAmazonDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }


    @Override
    public int delete(Long id, Long userId) {
        OrderAmazonDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(OrderAmazonDo entityDo, Long userId) {
//        entityDo.setDeleteBy(userId);
//        entityDo.setDeleteTime(new Date());
    }

    @Override
    public AmazonOrderDetailRes detail(Long id) {
        AmazonOrderDetailRes res = new AmazonOrderDetailRes();
        OrderAmazonDo amazonDo = dao.selectById(id);
        BeanUtils.copyProperties(amazonDo, res);
        LambdaQueryWrapper<OrderAmazonItemsDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderAmazonItemsDo::getOrderAmazonId, id);
        List<OrderAmazonItemsDo> itemsDoList = orderAmazonItemsDao.selectList(wrapper);
        List<AmazonOrderProductRes> productResList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(itemsDoList)) {
            for (OrderAmazonItemsDo itemsDo : itemsDoList) {
                AmazonOrderProductRes productRes = new AmazonOrderProductRes();
                BeanUtils.copyProperties(itemsDo, productRes);
                productResList.add(productRes);
            }
        }
        res.setProductResList(productResList);
        res.setOrderStatus(getOrderStatusStr(amazonDo.getOrderStatus()));
        res.setShipServiceLevel(getOrderShipTypeStr(amazonDo.getShipServiceLevel()));
        res.setOrderType(getOrderTypeStr(amazonDo.getOrderType()));
        List<OperateRes> operateResList = operateRecordDao.getOperateList(amazonDo.getId(), 4);
        res.setOperateResList(operateResList);

        return res;
    }

    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }


    @Override
    public PageResult getListPage(OrderAmazonQueryBo bo) {
        IPage<OrderAmazonDo> page = new Page<>(bo.getCurrent(), bo.getPageSize());
        page = this.page(page, queryBuild(bo));
        List<AmazonOrderPageRes> resList = handlerListAfter(page.getRecords());
        return new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
    }

    //查询分页列表之后对列表数据的处理
    private List<AmazonOrderPageRes> handlerListAfter(List<OrderAmazonDo> list) {
        List<AmazonOrderPageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (OrderAmazonDo amazonDo : list) {
                AmazonOrderPageRes res = new AmazonOrderPageRes();
                BeanUtils.copyProperties(amazonDo, res);
                res.setShipAddress((StringUtils.isBlank(amazonDo.getShipStateOrRegion()) ? "" : amazonDo.getShipStateOrRegion())
                        + (StringUtils.isBlank(amazonDo.getShipAddress()) ? "" : amazonDo.getShipAddress()));
                res.setOrderType((this.getOrderTypeStr(amazonDo.getOrderType())));
                res.setOrderStatus((this.getOrderStatusStr(amazonDo.getOrderStatus())));
                res.setShipServiceLevel(this.getOrderShipTypeStr(amazonDo.getShipServiceLevel()));
                if (amazonDo.getLastShipDate() != null)
                    res.setLastShipDate(TimeUtils.formatDate(amazonDo.getLastShipDate()));
                result.add(res);
            }
        }
        return result;
    }


    private IPage<OrderAmazonDo> pageInit(Map<String, String> map) {
        IPage<OrderAmazonDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private LambdaQueryWrapper<OrderAmazonDo> queryBuild(OrderAmazonQueryBo bo) {
        LambdaQueryWrapper<OrderAmazonDo> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotBlank(bo.getSku()), OrderAmazonDo::getCommoditySku, bo.getSku());
        lqw.like(StringUtils.isNotBlank(bo.getOrderNumber()), OrderAmazonDo::getAmazonOrderNumber, bo.getOrderNumber());
        lqw.like(StringUtils.isNotBlank(bo.getShipName()), OrderAmazonDo::getShipName, bo.getShipName());
        lqw.like(StringUtils.isNotBlank(bo.getShipPhone()), OrderAmazonDo::getShipPhone, bo.getShipPhone());
        lqw.ge(Objects.nonNull(bo.getStartTime()), OrderAmazonDo::getPurchaseDate, bo.getStartTime());
        lqw.le(Objects.nonNull(bo.getEndTime()), OrderAmazonDo::getPurchaseDate, bo.getEndTime());
        lqw.eq(StringUtils.isNotBlank(bo.getOrderStatus()), OrderAmazonDo::getOrderStatus, bo.getOrderStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getFulfillmentChannel()), OrderAmazonDo::getFulfillmentChannel, bo.getFulfillmentChannel());
        lqw.eq(StringUtils.isNotBlank(bo.getIsSend()), OrderAmazonDo::getIsSendOut, bo.getIsSend());
        lqw.eq(StringUtils.isNotBlank(bo.getShopId()), OrderAmazonDo::getShopId, bo.getShopId());
        lqw.eq(Objects.nonNull(bo.getCompanyId()), OrderAmazonDo::getCompanyId, bo.getCompanyId());
        lqw.orderByDesc(OrderAmazonDo::getLastUpdateDate);
        return lqw;
    }


    private String getStr(String str) {
        if (str == null) {
            return "";
        }
        return str;
    }

    private String getOrderTypeStr(String orderType) {
//        if ("StandardOrder".equals(orderType)) {
//            return "标准";
//        } else if (orderType.equals("Preorder")) {
//            return "预售";
//        }
//        return "标准";
        return StringsUtil.createI18Message(orderType);
    }

    private String getOrderShipTypeStr(String shipServiceLevel) {
//        if ("NextDay".equals(orderType)) {
//            return "次日达";
//        } else if (orderType.equals("Scheduled")) {
//            return "指定日";
//        } else if (orderType.equals("Expedited")) {
//            return "加急";
//        }
//        return "标准";
        if (!"NextDay".equals(shipServiceLevel) && !shipServiceLevel.equals("Scheduled") && !shipServiceLevel.equals("Expedited")) {
            return StringsUtil.createI18Message("Standard");
        }
        return StringsUtil.createI18Message(shipServiceLevel);

    }

    private String getOrderStatusStr(String orderStatus) {
//        if ("Pending".equals(orderStatus)) {
//            return "系统处理";
//        } else if (orderStatus.equals("Unshipped")) {
//            return "未发货";
//        } else if (orderStatus.equals("Shipped")) {
//            return "已发货";
//        } else if (orderStatus.equals("Canceled")) {
//            return "已取消";
//        } else if (orderStatus.equals("PartiallyShipped")) {
//            return "部分发货";
//        } else if (orderStatus.equals("PendingAvailability")) {
//            return "预约订单";
//        }
//        return "无法实现";
        return StringsUtil.createI18Message(orderStatus);

    }
}
